﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinkCard.Model;

namespace LinkCard.Dao
{
    public class CategoryDao : ITopLinkDao
    {
        public int Add(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objAdd = (Category)obj;
                db.AddToCategories(objAdd);
                rs = db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Update(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objUpdate = (Category)obj;
                var id = objUpdate.CategoryID;
                var oldObj = db.Categories.FirstOrDefault(t => t.CategoryID == id);
                if (oldObj != null)
                {
                    oldObj.ParentID = objUpdate.ParentID;
                    oldObj.Name = objUpdate.Name;
                    oldObj.Description = objUpdate.Description;
                    oldObj.Position = objUpdate.Position;
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Delete(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objDel = (Category)obj;
                var id = objDel.CategoryID;
                var oldObj = db.Categories.FirstOrDefault(t => t.CategoryID == id);
                if (oldObj != null)
                {
                    db.DeleteObject(oldObj);
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public Category GetById(long id)
        {
            var ct = new Category();
            try
            {
                var db = new TopLinkEntities();
                ct = db.Categories.FirstOrDefault(t => t.CategoryID == id);
            }
            catch (Exception)
            {
                throw;
            }
            return ct;
        }

        public List<Category> GetAll()
        {
            var lst = new List<Category>();
            try
            {
                var db = new TopLinkEntities();
                lst = db.Categories.ToList();
            }
            catch (Exception)
            {                
                throw;
            }
            return lst;
        }
    }
}
